<template>
  <div class="index">
    <div>

      <van-nav-bar title="编辑" left-text="返回" left-arrow @click-left="onClickLeft" />
      <div class="form">
        <!-- 礼物的名称 -->
        <van-row justify="center">

          <van-col span="8"><label for="name" style="margin-right:5%;font-size: 4vw;">礼物名称:</label></van-col>
          <van-col span="8"><input v-model="giftName" type="text"></van-col>


        </van-row>
        <p style="margin-top:-1px;font-size: 2vw;margin-left:15px">(名称仅自己可见)</p>

      </div>


    </div>
    <div>
    <van-radio-group v-model="checked" direction="horizontal" style="margin-top:15% ;">
      <van-radio name="1" icon-size="4vw" style="margin-left: 10%;">图片录音</van-radio>
      <van-radio name="2" icon-size="4vw" style="margin-left: 10% ;">上传视频</van-radio>
    </van-radio-group>
    <div class="choose" v-if = "checked === '1'">
    <div class="backg" >
      <!-- <label for="background" style="line-height:60px; font-size: 4vw;">选一个背景图：</label> -->
      <!-- <div v-if = "showImage">
        <img :src="imageUrl">
      </div> -->
      <van-uploader v-model="imageList" multiple 
       :max-count="1" 
       accept="image/*"
       :max-size="1024 * 1024"
       @oversize="imageOversize"
       @change="imaged"
       
       
       />
  
      <div class="back1" style="margin-left:5%">

        <!-- 轮播图 -->
        <!-- <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white" style="margin-left: 7%;">
          <van-swipe-item v-for="image in images" :key="image" :src="image.src" @click="selectImage(image)">
            <img :src="image" style="width: 100%; height: 100%; object-fit: cover;" />
          </van-swipe-item>
        </van-swipe>

        <van-icon name="arrow-left" />
        <van-icon name="arrow" /> -->

      </div>
    </div>
    <van-divider />
    <!-- 录音功能 -->
    <div class="container">
      <div class="preview">
        <audio ref="audio" controls style="width: 100%;"></audio>
      </div>

      <van-button round block type="primary" native-type="submit" style="width:30%; margin-left:14px;margin:auto "
        @click="startRecording" v-show="!isRecording">
        开始录音
      </van-button>

      <van-button round type="warning" @click="stopRecording" v-show="isRecording">
        停止录音
      </van-button>
      <van-button id="audio" round type="info" @click="playAudio" v-show="audioUrl"
        style="background-color:#1989FA;color:white;margin-top: 5%;">
        播放录音
      </van-button>

    </div>
  </div>
  <div class="choose" v-else-if="checked==='2'">
    <!-- 视频限制100Mb -->
    <!-- <van-uploader multiple
     :max-size="102400 * 1024"
     :max-count="1"
      @oversize="movieOversize" /> -->
      <form enctype="multipart/form-data" method="post">
        <input type="file" name="file" ref="videoInput" accept="video/*" @change="handleFileUpload" >
      </form>
     

</div>
</div>
  
    <div>
      <div style="margin-top: 5%; margin-bottom: 5%;">
        <van-button round block type="primary" native-type="submit" style="width:30%; margin:auto ; " @click="submit">
          预览
        </van-button>
      </div>

    </div>
  </div>
</template>
<script>
import { ref } from 'vue';
import { mapState } from 'vuex';
import { showToast } from 'vant';
import { mapActions } from 'vuex';

export default {
  //验证登录页面的tel值是否被正确传递到了状态管理器中
  computed: {
    ...mapState(
      ['tel', 'orderNumber']
    )
  },
  mounted() {
    console.log('orderNumber', this.orderNumber)
    console.log('tel:', this.tel)

  },


  setup() {
    const onClickLeft = () => history.back();
    // const images = [
    //   'https://img-qn.51miz.com/preview/element/00/01/17/92/E-1179271-142AD59F.jpg',
    //   'https://img2.baidu.com/it/u=3202947311,1179654885&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
    //   'https://img.tukuppt.com/photo-big/00/00/94/6152bc0ce6e5d805.jpg'
    // ];
    // const selectedImage = ref(null);
    const imageList = ref([
      
      // Uploader 根据文件后缀来判断是否为图片文件
      // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
      
    ]);
    const imageOversize = (file) => {
    console.log(file);
    showToast({
      message:'文件大小不能超过 1Mb',
      className: 'toastStyle'
    });
  };
  

    return {
      imageOversize,
      
      imageList,
      // images,
      onClickLeft,
      // selectedImage
    };

  },
  data() {

    return {
      videoOversize:100*1024*1024,  //100 Mb
      checked: '1', //选择上传图片录音或者视频（二选一） 1图片2视频
      giftName: '',//礼物名称
      mediaRecorder: null, // MediaRecorder 对象
      chunks: [], // 存储录制音频数据的数组
      isRecording: false, // 是否正在录制
      audioUrl: '', // 录制完成后的音频地址
    }
  },
  methods: {
    ...mapActions(['updateBackgroundImage']),

    imaged(event){
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        this.updateBackgroundImage(e.target.result);
      };
      reader.readAsDataURL(file);
    },
    handleFileUpload(){
      if (!file.type.startsWith("video/")){
        showToast({
          message:"只能上传视频文件",
          className:'toastStyle'
      });
        this.$refs.videoInput.value = null;
        return;
      }
      if (file.size>this.videoOversize) {
        showToast({
          message:"文件不能超过100Mb,建议使用剪映拍摄视频文件更小哦",
          className:'toastStyle'
        });
        this.$refs.videoInput.value = null;
        return;
      }
    },
  


    startRecording() {
      navigator.mediaDevices.getUserMedia({ audio: true }) // 获取麦克风权限
        .then(stream => {
          this.mediaRecorder = new MediaRecorder(stream) // 创建 MediaRecorder 实例
          this.mediaRecorder.start() // 开始录制
          this.isRecording = true
          this.chunks = []

          this.mediaRecorder.addEventListener('dataavailable', event => {
            this.chunks.push(event.data)
          })

          this.mediaRecorder.addEventListener('stop', () => {
            this.isRecording = false
            const blob = new Blob(this.chunks, { type: 'audio/mp3' }) // 将录制好的音频数据转成 Blob
            this.audioUrl = URL.createObjectURL(blob) // 创建 Blob 对象 URL
          })
        })
    },
    stopRecording() {
      if (this.mediaRecorder) {
        this.mediaRecorder.stop()
      }
    },
    playAudio() {
      const audio = this.$refs.audio
      audio.src = this.audioUrl // 设置音频地址
      audio.play()
    },
    //存入临时选中的图片
    // selectImage(image) {
    //   this.selectedImage = image;
    //   console.log("选择成功")
    // },
    

    //提交
    submit() {
      if (this.checked==='1'){
      if (!this.giftName && !this.imageList.length && !this.audioUrl) {    
          showToast({
            message:'请完善礼物哦',
            className:'toastStyle'
          });
          return
      } else {
        if (!this.giftName && !this.imageList.length) {
          showToast({
            message:'请输入它的名字和选择图片',
            className:'toastStyle'
          })
          return
        } else {
          if (!this.giftName && !this.audioUrl) {
            showToast({
              message:'请输入它的名字并录音',
              className:'toastStyle'
            })
            return
          } else {
            if (!this.imageList.length && !this.audioUrl) {
              showToast({
                message:'请选择图片并录音',
                className:'toastStyle'
              })
              return
            } else {
              if (!this.imageList.length) {
                showToast({
                  message:'还没选择图片呢',
                  className:'toastStyle'
                });
                return
              } else {
                if (!this.audioUrl) {
                  showToast({
                    message:'还没录音呢',
                    className:'toastStyle'
                  });
                  return
                }else{
                  if(!this.giftName){
                    showToast({
                      message:'还没输入礼物名字呢',
                      className:'toastStyle'
                    })
                    return
                  }
                }
              }
            }
          }
        }
      }
      if (this.giftName && this.imageList && this.audioUrl) {
        //存储数据
        this.$store.commit('updateGiftName', this.giftName);
        // this.$store.commit('updateBackgroundImage', this.imageList[0]);
        this.$store.commit('updateAudio', this.audioUrl)
        //跳转页面
        this.$router.push('/visit1')
      }


    }
    if(this.checked==='2'){
      if(!this.giftName&&!this.fileURL){
        showToast("请完善礼物哦");
        return;
      } else {
        if(!this.giftName){
          showToast('还没输入礼物名字呢');
          return;
        } else {
          if (!this.fileURL){
            showToast('请上传录制好的视频');
            return
          }
        }
      }
      if(this.giftName&&this.file){
        //存储数据
        this.$store.commit('updateGiftName',this.giftName);
        this.$store.commit('updateVideo',this.fileURL);
        //跳转页面
        this.$router.push('/visit1')
      }

    }
  }
}
  }

</script>
  
<style lang="less" scoped>
 .toastStyle {
  background: rgba(0,0,0,0.7) !important;
 }
.index {
  width: 100%;
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f1f1f1;
  //background-image:url(back.jpg)
}

.form {


  width: 100%;
  height: 75px;
  text-align: center;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 50px;
  margin-left: -30px
}

.form1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 75px;
  text-align: center;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 50px;
  margin-left: -30px
}

.form label {
  width: 200px;
  text-align: right;
  margin-right: 20px;
}

.form input {
  width: 250px;
  height: 30px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.choose {
  width: 600px;
  height: px;
  margin-top: 5%
}

.backg1 {
  width: 500px;
  height: 300px;
  margin-top: 0%;


}

.my-swipe {
  color: #fff;
  font-size: 20px;
  line-height: 200px;
  text-align: center;
  background-color: #f1f1f1;
  width: 80%;
  height: 300px;


  .container {
    height: 700px;
  }





}
</style>
  